<template>
  <div class="voice-input-wrapper" @mouseenter="showTooltip = true" @mouseleave="showTooltip = false">
    <div class="voice-input-button" @touchstart="startRecord" @touchend="stopRecord" :style="{
    'background': `radial-gradient(circle, rgba(255,255,255,0.23) ${100 - volumeLevel}%, rgba(0,255,0,0.5) ${100 - volumeLevel}%, rgba(0,200,0,0.7) 100%)`
  }">
      <image 
        :src="isActive ? '/static/icons/speak_on.svg' : '/static/icons/speak_off.svg'" 
        class="voice-icon"
      />
    </div>

    <!-- 悬浮提示 -->
    <div v-show="showTooltip" class="tooltip">
      语音输入
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue';

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['transcript']);

const showTooltip = ref(false);
const isActive = ref(false);
const volumeLevel = ref(0); // 0-100 的音量级别
let recordingTimer: number | null = null;
let volumeInterval: number | null = null;

function startRecord() {
  if (props.disabled) return;
  
  isActive.value = true;
  startVolumeSimulation(); // 开始模拟音量变化
  
  // 开始录音
  uni.getRecorderManager().start({
    duration: 60000, // 最长录音时间 60 秒
    sampleRate: 16000,
    numberOfChannels: 1,
    encodeBitRate: 96000,
    format: 'mp3',
    frameSize: 50
  });

  // 监听录音开始事件
  uni.getRecorderManager().onStart(() => {
    console.log('录音开始');
  });

  // 监听录音结束事件
  uni.getRecorderManager().onStop((res) => {
    console.log('录音结束，文件路径:', res.tempFilePath);
    // 这里应该调用语音识别服务
    recognizeSpeech(res.tempFilePath);
  });

  // 监听录音错误事件
  uni.getRecorderManager().onError((res) => {
    console.error('录音错误:', res);
    uni.showToast({
      title: '录音失败',
      icon: 'none'
    });
    stopRecord();
  });
}

function stopRecord() {
  isActive.value = false;
  
  // 停止录音
  uni.getRecorderManager().stop();
  
  // 清除定时器
  if (recordingTimer) {
    clearTimeout(recordingTimer);
    recordingTimer = null;
  }
  
  // 停止音量模拟
  if (volumeInterval) {
    clearInterval(volumeInterval);
    volumeInterval = null;
  }
  
  volumeLevel.value = 0;
}

// 模拟音量变化（因为微信小程序不提供实时音量反馈）
function startVolumeSimulation() {
  volumeLevel.value = 0;
  
  if (volumeInterval) {
    clearInterval(volumeInterval);
  }
  
  volumeInterval = setInterval(() => {
    // 模拟音量波动
    volumeLevel.value = Math.min(Math.max(volumeLevel.value + (Math.random() * 20 - 5), 0), 100);
  }, 200);
}

// 语音识别（这里需要调用后端API或微信的语音识别接口）
function recognizeSpeech(tempFilePath: string) {
  // 在实际应用中，这里应该调用微信的语音识别接口或者自己的后端API
  // 微信提供了语音识别接口，但需要服务端配合
  // 参考文档: https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/short-link/shortlink.generate.html
  
  // 作为示例，我们直接返回一些测试文本
  setTimeout(() => {
    emit('transcript', '这是语音识别的结果');
    uni.showToast({
      title: '语音识别成功',
      icon: 'success'
    });
  }, 1000);
}

onUnmounted(() => {
  stopRecord();
});
</script>

<style scoped lang="scss">
.voice-input-wrapper {
  position: relative;
  display: inline-flex;

  .tooltip {
    position: absolute;
    bottom: calc(100% + 8px);
    left: 50%;
    transform: translateX(-50%);
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    white-space: nowrap;
    opacity: 0;
    transition: opacity 0.2s ease;
    pointer-events: none;
    z-index: 10;

    /* 提示框底部的小箭头 */
    &::after {
      content: '';
      position: absolute;
      top: 100%;
      left: 50%;
      transform: translateX(-50%);
      border-width: 4px;
      border-style: solid;
      border-color: rgba(0, 0, 0, 0.7) transparent transparent transparent;
    }
  }

  &:hover .tooltip {
    opacity: 1;
  }
}

.voice-input-button {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 26px;
  cursor: pointer;
  transition: background 0.1s ease;
  position: relative;
  overflow: hidden;

  &:hover {
    background-color: rgba(255,255,255,0.18);
  }

  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: v-bind('volumeLevel + "%"');
    background: rgba(0, 200, 0, 0.5);
    transition: height 0.1s ease;
    z-index: 0;
  }

  .voice-icon {
    position: relative;
    z-index: 1;
    width: 24px;
    height: 24px;
  }
}
</style>